package com.luoxiang.socialandroid.activity;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.HOSTAUDIT;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.IMTOKEN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_PHONE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.USERID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.USER_NAME;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.adapter.SelectipAdapter;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.PhonechangeBean;
import com.luoxiang.socialandroid.bean.SelectIpBean;
import com.luoxiang.socialandroid.bean.SendcodeBean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.luoxiang.socialandroid.utils.ThendTimeUtil;
import com.netease.yunxin.kit.corekit.im.IMKitClient;
import com.netease.yunxin.kit.corekit.im.login.LoginCallback;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class PhoneChangeActivity extends BaseActivity {
    private TextView tv_beginphone, btn_genggai, tv_jiabaliu;
    private Button btn_sendcode;
    private EditText edit_newphone, edit_email;
    private PopupWindow popupWindow;
    private RecyclerView recyclerView;
    private SelectipAdapter adapter;
    private RelativeLayout editView;
    private ImageView imageOpenStats;
    private Boolean isAbleSendCode = false;

    private void ThendTime() {
        ThendTimeUtil.Therd(60, new ThendTimeUtil.timeBack() {
            @Override
            public void back(int time, boolean n) {
                if (n) {
                    btn_sendcode.setText(R.string.mi_huoquyanzhengma);

                    btn_sendcode.setOnClickListener(new CustomClickListener() {
                        @Override
                        protected void onSingleClick() {
                            String edt_phone = edit_newphone.getText().toString();
                            getLoginbycode(tv_jiabaliu.getText().toString() + " " + edt_phone, "bind", MmkvUtil.INSTANCE.decodeString(TOKEN));
                        }

                        @Override
                        protected void onFastClick() {

                        }
                    });
                } else {
                    btn_sendcode.setText("重新发送" + time + "(S)");
                    btn_sendcode.setTextColor(Color.parseColor("#999999"));
                    btn_sendcode.setBackgroundResource(R.drawable.shape_huoquyanz);
                }
            }
        });
    }

    @Override
    protected void initListener() {
        findViewById(R.id.icon_back).setOnClickListener(view -> finish());
        findViewById(R.id.tv_jiabaliu).setOnClickListener(view -> {
            imageOpenStats.setImageResource(R.mipmap.ic_login_close);
            popupWindow.showAsDropDown(editView, 0, 0);
        });
        popupWindow.setOnDismissListener(() ->
                imageOpenStats.setImageResource(R.mipmap.ic_login_open)
        );
        btn_sendcode.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                if (!isAbleSendCode){
                    ToastUtils.showShort("请输入有效手机号");
                    return;
                }
                //开始倒计时
                String edt_phone = edit_newphone.getText().toString();
                MmkvUtil.INSTANCE.encode(KEY_PHONE, edt_phone);
                getLoginbycode(tv_jiabaliu.getText().toString() + " " + edt_phone, "bind", MmkvUtil.INSTANCE.decodeString(TOKEN));
            }

            @Override
            protected void onFastClick() {}
        });
        edit_newphone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void afterTextChanged(Editable editable) {
                if (edit_newphone.getText().length() >= 7) {
                    isAbleSendCode = true;
                } else {
                    isAbleSendCode = false;
                }
            }
        });
        edit_email.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void afterTextChanged(Editable editable) {
                //代表没有输入
                if (edit_email.getText().length() < 4) {
                    btn_genggai.setBackground(getResources().getDrawable(R.drawable.shape_buxuanzhong));
                    btn_genggai.setTextColor(Color.parseColor("#FFFFFF"));
                } else {
                    btn_genggai.setBackground(getResources().getDrawable(R.drawable.shape_btnblueban));
                    btn_genggai.setTextColor(Color.parseColor("#FFFFFF"));
                    btn_genggai.setOnClickListener(new CustomClickListener() {
                        @Override
                        protected void onSingleClick() {
                            String s = edit_email.getText().toString();
                            String edt_phone = edit_newphone.getText().toString();
                            getinTiePhone(EXTRA, MmkvUtil.INSTANCE.decodeString(TOKEN), s, tv_jiabaliu.getText().toString() + " " + edt_phone);
                        }

                        @Override
                        protected void onFastClick() {}
                    });
                }
            }
        });
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_phone_change);
        setStatusBarTranslucent();

    }

    /**
     * 获取验证码的方法
     *
     * @param phone
     * @param op
     */
    private void getLoginbycode(String phone, String op, String token) {
        NetUtils2.getInstance().getApiService().getsendCode(phone, op, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading();
                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        Gson gson = new Gson();
                        SendcodeBean sendcodeBean = gson.fromJson(decryptStr, SendcodeBean.class);
                        if (sendcodeBean != null) {
                            int code = sendcodeBean.getCode();
                            LogUtils.i("code", code);
                            if (code == 0) {
                                //跳转
                                ToastUtils.showShort(R.string.mi_huoquyanzhengmachenggong);
                                ThendTime();
                            } else {
                                ToastUtils.showShort(sendcodeBean.getMsg());
                            }
                        }
                        clearLoading();

                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {
                        clearLoading();
                    }
                });
    }

    private void logoutIM(){
        MmkvUtil.INSTANCE.encode(TOKEN, "");
        MmkvUtil.INSTANCE.encode(ACCID, "");
        MmkvUtil.INSTANCE.encode(IMTOKEN, "");
        MmkvUtil.INSTANCE.encode(HOSTAUDIT, "");
        MmkvUtil.INSTANCE.encode(USER_NAME, "");
        MmkvUtil.INSTANCE.encode("phone", "");
        MmkvUtil.INSTANCE.encode(USERID, "");
        MmkvUtil.INSTANCE.encode("datingModeId", "");
        MmkvUtil.INSTANCE.encode("emotioRelationId", "");
        MmkvUtil.INSTANCE.encode("targetAgeId", "");
        MmkvUtil.INSTANCE.encode("sexpait", "");
        IMKitClient.logoutIM(new LoginCallback<Void>() {
            @Override
            public void onError(int i, @NonNull String s) {
                ToastUtils.showShort(s);
            }

            @Override
            public void onSuccess(@Nullable Void unused) {
            }
        });
    }

    @Override
    protected void initView() {
        tv_beginphone = findViewById(R.id.tv_beginphone);
        btn_sendcode = findViewById(R.id.btn_sendcode);
        edit_newphone = findViewById(R.id.edit_newphone);
        edit_email = findViewById(R.id.edit_email);
        btn_genggai = findViewById(R.id.btn_genggai);
        tv_jiabaliu = findViewById(R.id.tv_jiabaliu);
        imageOpenStats = findViewById(R.id.imageOpenStats);
        editView = findViewById(R.id.editView);
        Intent intent = getIntent();
        String phonenumber = intent.getStringExtra("phonenumber");
        tv_beginphone.setText(getString(R.string.mi_yuanshoujihao) + phonenumber);

        View view1 = LayoutInflater.from(PhoneChangeActivity.this).inflate(R.layout.popup_selectid, null, false);
        popupWindow = new PopupWindow(view1, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        recyclerView = popupWindow.getContentView().findViewById(R.id.recySelectIp);

        getCountryMobilePrefixList(EXTRA);
    }

    private void getinTiePhone(String extra, String token, String code, String phone) {
        NetUtils.getInstance().getApiService().getinTiePhone(extra, token, code, phone)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStrgenghuan", decryptStr);
                        Gson gson = new Gson();
                        PhonechangeBean phonechangeBean = gson.fromJson(decryptStr, PhonechangeBean.class);
                        if (phonechangeBean.getCode() == 0) {
                            ToastUtils.showShort(R.string.mi_genghuanshoujihaochenggong);
                            logoutIM();
                            Intent intent = new Intent(PhoneChangeActivity.this, LoginActivity.class);
                            startActivity(intent);
                            HomeActivity.instance.finish();
                            finish();
                        } else {
                            ToastUtils.showShort(phonechangeBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getCountryMobilePrefixList(String extra) {
        getRequest();
        NetUtils2.getInstance().getApiService().getCountryMobilePrefixList(extra)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {}

                    @Override
                    public void onNext(NumberBean value) {
                        String data = value.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                            com.luoxiang.lib_common.utils.LogUtils.i("decryptSelectid", decryptStr);
                            Gson gson = new Gson();
                            SelectIpBean selectIpBean = gson.fromJson(decryptStr, SelectIpBean.class);
                            if (selectIpBean.getCode() != 0) {
                                ToastUtils.showShort(selectIpBean.getMsg());
                            } else {
                                //在这里进行逻辑操作
                                adapter = new SelectipAdapter(selectIpBean.getData().getResult());
                                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(PhoneChangeActivity.this);
                                recyclerView.setLayoutManager(linearLayoutManager);
                                recyclerView.setAdapter(adapter);
                                adapter.setOnAddClickListener(new SelectipAdapter.OnAddClickListener() {
                                    @Override
                                    public void onItemClicks(String quhao) {
                                        popupWindow.dismiss();
                                        //点击区号以后在这里处理
                                        tv_jiabaliu.setText("+" + quhao);
                                    }
                                });
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("erroroHttp", e.toString());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
}